import type { AnyFunction } from "@/utils/types";
import { useEffect } from "react";
import { debounce } from "@/utils";

interface UseWindowSizeOptions {
	wait?: number;
	once?: boolean;
	immediate?: boolean;
	listenerOptions?: AddEventListenerOptions | boolean;
}

function useWindowSizeFn(fn: AnyFunction, options: UseWindowSizeOptions = {}) {
	const { wait = 150, immediate } = options;
	let handler = () => {
		// console.log("尺寸变化");
		fn();
	};
	const handleSize = debounce(handler, wait);

	const start = () => {
		if (immediate) handleSize();
		window.addEventListener("resize", handleSize);
	};

	const stop = () => {
		window.removeEventListener("resize", handleSize);
	};

	useEffect(() => {
		start();
		return () => {
			stop();
		};
	}, []);

	return { start, stop };
}

export { useWindowSizeFn, type UseWindowSizeOptions };
